#include "Socket.hpp"
#include "common.hpp"
#include "Protocol.hpp"
#include <iostream>
#include <string>
#include <memory>

using namespace SocketModule;

void Usage(std::string proc)
{
    std::cerr << "Usage :" << proc << "service_ip  service_port" << std::endl;
}

void GetDataFromStdin(int *x,int *y,char* oper)
{
    std::cout << "Please Enter x:";
    std::cin >> *x;
    std::cout << "Please Enter y:";
    std::cin >> *y;
    std::cout << "Please Enter oper:";
    std::cin >> *oper;  
}

int main(int argc,char* argv[])
{
    if(argc != 3)
    {
        Usage(argv[0]);
        exit(ARGV_ERROR);
    }

    std::string ip (argv[1]);
    uint16_t port = std::stoi(argv[2]);

    std::shared_ptr<Socket> client = std::make_shared<TcpSocket>();
    client->BuildTcpClientSocketMethod();

    if(client->Connect(ip,port) != 0)
    {
        // 连接失败
        std::cerr << "connect error" << std::endl;
        exit(CONNECT_ERROR);
    }

    std::unique_ptr<Protocol> protocol = std::make_unique<Protocol>();
    std::string resp_buffer;

    // 连接服务器
    while(true)
    {
        // 1.从标准输入流当中获取数据。
        int x , y;
        char oper;
        GetDataFromStdin(&x,&y,&oper);
        
        // 2.构建一个请求 -> 可以直接发送字符串
        std::string req_str = protocol->BuildRequestString(x,y,oper);

        // 3.发送请求
        client->Send(req_str);
 
        // 4.获取应答
        Response resp;
        bool res = protocol->GetResponse(client,resp_buffer,&resp);
        if(res == false)
        {
          break;
        }

        // 5.显示结果
        resp.ShowResult();
    }
    client->Close();

    return 0;
}
